package net.bplaced.streetfighter.fragment;

import java.util.ArrayList;

import net.bplaced.streetfighter.R;
import net.bplaced.streetfighter.adapter.GoalGetterAdapter;
import net.bplaced.streetfighter.lib.async.task.GoalGetterLoaderTask;
import net.bplaced.streetfighter.lib.model.GoalGetter;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class GoalGetterFragment
        extends Fragment {

    private RelativeLayout view = null;
    private GoalGetterAdapter goalGetterAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        this.view = (RelativeLayout) inflater.inflate(R.layout.view_goalgetter, container, false);

        this.prepareView();
        this.startFetchGoalgetter();

        return this.view;
    }

    private void prepareView() {

        final ListView list = (ListView) this.view.findViewById(R.id.goalgetter_list);
        list.setDividerHeight(0);

        this.goalGetterAdapter = new GoalGetterAdapter(this.getActivity(), new ArrayList<GoalGetter>());

        list.setAdapter(this.goalGetterAdapter);
    }

    private void startFetchGoalgetter() {

        final GoalGetterLoaderTask task =
                new GoalGetterLoaderTask(this.getActivity(), this.getResources().getString(
                        R.string.goalgetter_progress_message), this.onFinishedLoading);
        task.execute();
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<GoalGetter[]>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<GoalGetter[]>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<GoalGetter[]> result) {

                    if (result != null) {
                        if (result.getContent() != null) {

                            GoalGetterFragment.this.goalGetterAdapter.addAll(result.getContent());

                        } else {

                            Toast.makeText(GoalGetterFragment.this.getActivity(), result.getErrorMessage(),
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                };
            };
}